package bdqn.sl.bolg_sl.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    //后台监控 ServletRegistrationBean
    // 因为 SpringBoot 内置了servlet容器 ,所以没有web.xml 替代方法ServletRegistrationBean
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        //后台需要人登录 ,账号密码配置
        Map<String, String> inParameters = new HashMap();
        //key 为固定参数
        inParameters.put("loginUsername", "a");
        inParameters.put("loginPassword", "1");
        //允许谁能访问
        inParameters.put("allow", "");  //"" 允许所有人访问
        //禁止谁能访问
        // nParameters.put("sl","");//
        bean.setInitParameters(inParameters);//设置初始化参数
        return bean;
    }

    //过滤器 filter
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());
        //可以过滤哪些请求;
        Map<String, String> inParameters = new HashMap();
        //这些东西不进行统计 js css druid/*
        inParameters.put("exclusions", "*.js,*.css,/druid/*");
        bean.setInitParameters(inParameters);
        return bean;
    }
}
